package com.zhihaoliang.busEncy.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.zhihaoliang.busEncy.callback.IBusiLeftCallback
import com.zhihaoliang.busEncy.databinding.ItemBusiLeftBinding
import com.zhihaoliang.busEncy.model.BusiLeftBean

class BusiLeftAdapter(val callback: IBusiLeftCallback) :
    RecyclerView.Adapter<BusiLeftAdapter.ViewHolder>() {

     val listData: MutableList<BusiLeftBean> = ArrayList();

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            ItemBusiLeftBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.viewModel = listData[position]
        holder.binding.callback = callback
    }

    override fun getItemCount(): Int {
        return listData.size
    }

    fun updateListData(list: MutableList<BusiLeftBean>) {
        listData.clear()
        listData.addAll(list)
        notifyDataSetChanged()
    }

    fun updateListIndex(item: BusiLeftBean) {
        for (itemIndex in listData.indices) {
            if (!listData[itemIndex].isSelect) {
                setSelect(itemIndex, true)
            } else if (listData[itemIndex] == item) {
                setSelect(itemIndex, false)
            }
        }
    }

    private fun setSelect(index: Int, isSelect: Boolean) {
        listData[index].isSelect = isSelect
        notifyItemChanged(index)

        if (index > 0) {
            listData[index - 1].isShowBot = !isSelect
            notifyItemChanged(index - 1)
        }

        if (index < listData.size - 1) {
            listData[index + 1].isShowTop = !isSelect
            notifyItemChanged(index + 1)
        }
    }


    class ViewHolder(var binding: ItemBusiLeftBinding) : RecyclerView.ViewHolder(binding.root)

}